package org.brisling.ethic.queryService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ExportExcelDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.ExportUtil;
import org.brisling.common.util.JsonUtil;
import org.brisling.common.util.WhereUtil;
import org.brisling.ethic.domain.DailyEvaluation;
import org.brisling.ethic.domain.EthicEvaluate;
import org.brisling.ethic.domain.VODailyEvaluate;
import org.brisling.ethic.domain.VOEthicEvaluateSub;
import org.brisling.ethic.domain.VOGiftReturn;
import org.brisling.sysman.domain.SysLob;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.service.LobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/recordEthicEvaluate/query")
public class QueryRecordEthicEvaluateService extends AbstractBaseQueryService<EthicEvaluate>{
	
	
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;	
//	@Autowired
//	private QueryDictionaryService dicService;
	
	@Autowired
	private QueryDicSubjectService qryDicSubjectService;
	
	
	@Autowired
	private QueryDailyEvaluationService qryDailyEvaluationService;
	
	@Autowired
	private QueryGiftService qryGiftService;
	
	@Autowired
	private LobService lobService;
	
	@Autowired
	protected QueryDictionaryService dicService;
	
	private String title = "年度考评记录";
	
	
	private String queryModule = "query_ethic_all";
//	private String deptid_code = "depart_code";
	
	public QueryRecordEthicEvaluateService(){
		this.moduleName = ConstSysParam.MODULE_ETHIC_EVALUATE;
		this.subSystem = ConstSysParam.SUBSYSTEM_ETHIC;
		this.tableName = ConstSysParam.VIEW_PREFIX +this.getTableName(EthicEvaluate.class);
		this.clazz = EthicEvaluate.class;
		
		typeMap = this.getTypeMap(clazz);
		
		orderMap = new LinkedHashMap<String,String>();
		
		orderMap.put("bizno",null);		
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return new ModelAndView("/ethic/record_ethic_evaluate/main");
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return new ModelAndView("/ethic/record_ethic_evaluate/editDlg");
	}
	
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		return new ModelAndView("/ethic/record_ethic_evaluate/popMain");
	}
	

	@RequestMapping("/getListDomain.action")
	public ListDomain<EthicEvaluate> getListDomain(@RequestBody(required=false) String body){		
			
		ListDomain<EthicEvaluate> eeList = this.getSimpleListDomain(body);
		Integer eval_year = Calendar.getInstance().get(Calendar.YEAR);
		return setRecord(eeList, String.valueOf(eval_year));
	}
	//select wm_concat(v.EVAL_CONTENT || '\n') daily_evaluate, eval_id, EXTRACT(YEAR FROM createat) eval_year
	// FROM V_ETHIC_DAILY v where EVAL_CONTENT is not null  group by eval_id, EXTRACT(YEAR FROM createat) order by eval_year
    
	
	@RequestMapping("/getSimpleListDomain.action")
	public ListDomain<EthicEvaluate> getSimpleListDomain(@RequestBody(required=false) String body){		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_ethic_all"))
			conditionMap = this.addDeptConditionToMap(userid,conditionMap, "org_id");	
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		param_map =param_map == null?new HashMap<String,String>():param_map;
		param_map.put("status_ge","3");
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);	
		orderMap = new LinkedHashMap<String,String>();
		orderMap.put("depart_code", null);
		orderMap.put("composite_score","desc");
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, orderMap, false);	
	}
	/**
	 * 设置日常考评和红包礼品退还字段
	 */
	private ListDomain<EthicEvaluate> setRecord(ListDomain<EthicEvaluate> eeList, String eval_year) {		
		
		if (eeList != null) {
			List<VODailyEvaluate> deList = null;
			List<VOGiftReturn> grList = null;
			
			String _year = null;
			String _uid = null;
			for (EthicEvaluate e : eeList.getRows()) {
				
				_year = e.getEvaluate_year();
				_uid = e.getPerson_code();
				try {
					deList = qryDailyEvaluationService.getVODailyEvaluateByEvalateYearAndUser(_year,_uid);
					grList = qryGiftService.getVOGiftByEvalateYearAndUser(_year,_uid);
				} catch (DangerousOperatorException ex) {
					ex.printStackTrace();
				}
				e = setDailyEvaluate(e, deList);
				e = setGiftReturn(e, grList);
			}
		}
		return eeList;
	}
	
	/**
	 * 设置日常考评字段
	 * @param 
	 * @return
	 */
	private EthicEvaluate setDailyEvaluate(EthicEvaluate ee, List<VODailyEvaluate> lists) {
		for (VODailyEvaluate e : lists) {
			if (e.getDoct_code().toString().equals(ee.getPerson_code())) {
				ee.setDaily_evaluate(e.getDaily_evaluate());
			}
		}
		return ee;
	}
	
	/**
	 * 设置红包礼品退还字段
	 */
	private EthicEvaluate setGiftReturn(EthicEvaluate ee, List<VOGiftReturn> lists) {
		for (VOGiftReturn e : lists) {
			if (e.getDoct_code().toString().equals(ee.getPerson_code())) {
				ee.setGift_return(e.getGift_return());
			}
		}
		return ee;
	}
	
	
	/**
	 * 获取自我考评实体集合
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getSelfListDomain.action")
	public ListDomain<EthicEvaluate> getSelfListDomain(@RequestBody(required=false) String body){		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		param_map.put("person_code", userid);
		param_map.put("status","0");
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);	
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, orderMap, true);				
	}
	
	/**
	 * 获取部门考评实体结果集
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<EthicEvaluate> getDeptListDomain(@RequestBody(required=false) String body){		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		
//		param_map.put("status","1");
		String deptids = this.getUserDeptids(userid);
		param_map.put("org_id_in", deptids);
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		
		
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, orderMap, true);		
		
	}
	
	/**
	 * 获取党支部考评实体结果集
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getPartyListDomain.action")
	public ListDomain<EthicEvaluate> getPartyListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		
		param_map.put("status","2");
		
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		
		
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, orderMap, true);		
		
	}
	/**
	 * 获取全院考评实体结果集
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getAllListDomain.action")
	public ListDomain<EthicEvaluate> getAllListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		
		
		//判断是否管理岗用户
		String userid = shiroSecurityService.getCurrentUserIdentify();
		
		String superUserIdentify=SysConfig.getConfig(ConstSysParam.SUPER_USER_IDENTIFY);
		if(  !isManageJob(userid) && (userid.compareTo(superUserIdentify)!=0) && (!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, queryModule))){
			param_map.put("person_code", userid);
		}
		
		
		param_map.put("status_ge","4");
		LinkedHashMap<String,String> order_map = new LinkedHashMap<String,String>();
		
		order_map.put("evaluate_year", "desc");
		if(param_map !=null){
			if(!param_map.containsKey("person_code")){			
				order_map.put("composite_score", "desc");
			}
		}
		
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		ListDomain<EthicEvaluate> eeList = super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, order_map, false);	
		eeList = setRecord(eeList, param_map.get("evaluate_year_like"));
		return eeList;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/getFinishListDomain.action")
	public ListDomain<EthicEvaluate> getFinishListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		
		param_map.put("status","4");
		
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
	
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, orderMap, true);		
		
	}
	
	@RequestMapping("/getList.action")
	public List<EthicEvaluate> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	public List<EthicEvaluate> getListAll(Map<String, String> map){	
		
		String sql = "";
		String whereCorse = null;					
			
		whereCorse = WhereUtil.getConditionWhereCorse(map,typeMap);
		System.out.println("whereCorse: " +whereCorse);		
		
		if(whereCorse!=null){			
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			return super.getAllList(sql);
		}
		return new ArrayList<EthicEvaluate>();		
		
	}
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public EthicEvaluate getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public EthicEvaluate getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}	
	
	
	@RequestMapping("/getListByField.action")
	public List<EthicEvaluate> getListByField(@RequestParam(value="field",required=false) String field,@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return super.getListByIdentify(field,fieldVal);
	}
	

	@RequestMapping("/getSubListDomainByMainId.action")
	public Object getSubListDomainByMainId(@RequestParam(required=false) Long lobid){		
		
		if(lobid!=null && lobid>0){			 
			SysLob domain = lobService.getOne(lobid);
			if(domain!=null && domain.getId()!=null){	
				String subContent = StringUtils.normalizeSpace(domain.getLob_contents());
				if(subContent != null){
					List<Object> sublist = JsonUtil.bodyToList(subContent, VOEthicEvaluateSub.class);
					return sublist;
				}
				
			}
		}
				
		return initSubList();
	}
	
	/**
	 * 查询获取加扣分项
	 * @param eval_year	考评年度
	 * @param uid		
	 * @return
	 */
	@RequestMapping("/getAddMinScore.action")
	public Map<String,Double> getAddMinScore(
				@RequestParam(value="uid",required=false)String uid,
				@RequestParam(value="eval_year",required=false)String eval_year){
		if(uid==null){
			return null;
		}
		if(eval_year==null){
			eval_year = Calendar.YEAR+"";
		}		
		
		List<DailyEvaluation> lists =qryDailyEvaluationService.getYearAndUserListAll(eval_year,uid);
		
		Double add_score = 0.0;
		Double min_score = 0.0;
		Map<String,Double> ret = new HashMap<String,Double>();
		if(lists!=null && lists.size()>0){
			for(DailyEvaluation de:lists){
				String _type = de.getAddorminus_type();
				if(_type!=null){
					_type = _type.trim();
					if(_type.indexOf("加分")>=0){
						add_score +=Double.parseDouble(de.getScore());
					}else{
						min_score +=Double.parseDouble(de.getScore());
					}
				}
			}
		}
		ret.put("add_score",add_score);
		ret.put("mark_score",min_score);
		return ret;
		
	}
	
	private ListDomain<Object> initSubList(){
		return qryDicSubjectService.getInitListDomain();
	}
	
	/**
	 * 导出excel记录
	 * @param body
	 * @param response
	 */
	@RequestMapping("/exportExcel.action")
	public void exportExcel(@RequestBody(required=false) String body,HttpServletResponse response){
		
		
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_ethic_all"))
			conditionMap = this.addDeptConditionToMap(userid,conditionMap, "org_id");	
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		param_map =param_map == null?new HashMap<String,String>():param_map;
		param_map.put("status_ge","3");
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		
		
		orderMap = new LinkedHashMap<String,String>();
		orderMap.put("depart_code", null);
		orderMap.put("composite_score","desc");
		List<EthicEvaluate> lists=this.getListByConditionAndOrder(param_map,typeMap,orderMap,true,false);
		
		String sqlid = "ethic_record_export";
		String configStr = dicService.getSqlByBizcode(sqlid);
		
		ObjectMapper mapper = JsonUtil.getMapper();
		JavaType _javaType = mapper.getTypeFactory().constructCollectionType(List.class, ExportExcelDomain.class);

		List<ExportExcelDomain> list = null;
		try {
			list =  mapper.readValue(configStr, _javaType);
		}catch(Exception e){
			e.printStackTrace();
		}
		ExportUtil<EthicEvaluate> eu = new ExportUtil<EthicEvaluate>(title,list,lists);
		try {
			eu.exportByDomain(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
